import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.resps.Tuple;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RedisDemoZSet {
    public static void test01(Jedis jedis) {
        System.out.println("zadd 和 zrange");
        jedis.flushAll();
        jedis.zadd("key", 10, "zhangsan");
        Map<String, Double> map = new HashMap<>();
        map.put("lisi", 20.0);
        map.put("wangwu", 30.0);
        jedis.zadd("key", map);
        List<String> members = jedis.zrange("key", 0, -1);
        System.out.println("members:" + members);
        List<Tuple> zrangedWithScores = jedis.zrangeWithScores("key", 0, -1);
        System.out.println("zrangedWithScores = " + zrangedWithScores);

        String element = zrangedWithScores.get(0).getElement();
        double score = zrangedWithScores.get(0).getScore();
        System.out.println("element:" + element + ", score:" + score);
    }

    public static void test02(Jedis jedis) {
        System.out.println("zcard");
        jedis.flushAll();
        jedis.zadd("key", 10, "zhangsan");
        jedis.zadd("key", 20, "lisi");
        jedis.zadd("key", 30, "wangwu");
        long len = jedis.zcard("key");
        System.out.println("len:" + len);
    }

    public static void test03(Jedis jedis) {
        System.out.println("zrem");
        jedis.flushAll();
        jedis.zadd("key", 10, "zhangsan");
        jedis.zadd("key", 20, "lisi");
        jedis.zadd("key", 30, "wangwu");
        long n = jedis.zrem("key", "zhangsan");
        System.out.println("n:" + n);
        List<String> result = jedis.zrange("key", 0, -1);
        System.out.println("result:" + result);
    }

    public static void test04(Jedis jedis) {
        System.out.println("zscore");
        jedis.flushAll();
        jedis.zadd("key", 10, "zhangsan");
        jedis.zadd("key", 20, "lisi");
        jedis.zadd("key", 30, "wangwu");
        Double zscore = jedis.zscore("key", "zhangsan");
        System.out.println("zscore:" + zscore);
    }

    public static void test05(Jedis jedis) {
        System.out.println("获取下标（排名） zrank");
        jedis.flushAll();
        jedis.zadd("key", 10, "zhangsan");
        jedis.zadd("key", 20, "lisi");
        jedis.zadd("key", 30, "wangwu");
        Long zrank = jedis.zrank("key", "zhangsan");
        System.out.println("zrank:" + zrank);
    }


    public static void main(String[] args) {
        JedisPool jedisPool = new JedisPool("tcp://127.0.0.1:8888");
        try (Jedis jedis = jedisPool.getResource()) {
//            test01(jedis);
//            test02(jedis);
//            test03(jedis);
//            test04(jedis);
            test05(jedis);
        }
    }
}
